--#include "data\functions\Activity\OpenServer\OpenServerCommon.lua" once
--团购活动

function IsInOpenServerSuperPurchaseDay()
    local openday = System.getDaysSinceOpenServer()
    local startDay = OpenServerCfg.superPurchase.openDay or 1
    local endDay = OpenServerCfg.superPurchase.endDay or OpenServerCfg.OpenServerDay
    if openday >= startDay and openday <= endDay then
        return true
    end
    return false
end

function IsInOpenServerSuperPurchaseDailyEndDay()
    local openday = System.getDaysSinceOpenServer()
    local startDay = OpenServerCfg.superPurchase.openDay or 1
    local endDay = OpenServerCfg.superPurchase.endDay or OpenServerCfg.OpenServerDay
    if openday > 1 and openday <= endDay + 1 then
        return true
    end
    return false
end

-- 活动结束
function OpenServerSuperPurchaseEnd()
    if not IsInOpenServerSuperPurchaseDailyEndDay() then
        return
    end
    local ssVar = System.getStaticVar()
    if not ssVar.openserver_superpurchase_total_buycount then
        ssVar.openserver_superpurchase_total_buycount = 0
    end
    local day = System.getDaysSinceOpenServer()
    local config = OpenServerCfg.superPurchase

    local rankPtr = Ranking.getRanking(RankList[RANK_OS_SUPER_PURCHASE].strName)
    local rankCount = Ranking.getRankItemCount(rankPtr)
    for idx = 1, rankCount do
        local item = Ranking.getItemFromIndex(rankPtr, idx-1)
        if item then
            local actorid = tonumber(Ranking.getId(item))
            local data = Ranking.getSub(item, 1)
            local dataTable
            if not data or data == "" then
                dataTable = {}
            else
                dataTable = BaseFuc_unserialize(data)
            end
          
            if dataTable.myBuyCount and dataTable.myBuyCount > 0 then
                local rewardCfg = config.Rewards[day]
                if not rewardCfg then
                    rewardCfg = config.Rewards[#config.Rewards]
                end
                for idx = 1, #rewardCfg do
                    if (dataTable.myDayData and dataTable.myDayData[idx] and dataTable.myDayData[idx] == 1) or
                        ((not dataTable.myDayData or not dataTable.myDayData[idx] or dataTable.myDayData[idx] == 0) and
                            ssVar.openserver_superpurchase_total_buycount >= rewardCfg[idx].buyCount)
                        then
                        local rewards = rewardCfg[idx].Awards
                        local title = Lang.ScriptTips.OpenServer017
                        local content = Lang.ScriptTips.OpenServer018
                        Awards.GiveToMailById(actorid, rewards, title, content, LogIds.OpenServerSuperPurchaseLogId, Lang.LogTips.OpenServerSuperPurchase, dataTable.vocation, dataTable.sex)
                    end
                end
            end
        end
    end
    gRankMgr_Clear(RANK_OS_SUPER_PURCHASE)
    ssVar.openserver_superpurchase_total_buycount = 0
end

-- 打包数据
function SendOpenServerSuperPurchaseData(sysarg)
    if not IsInOpenServerSuperPurchaseDay() then
        return
    end
    local ssVar = System.getStaticVar()

    local config = OpenServerCfg.superPurchase
    if not config then
        return
    end

    local time = System.getCurrMiniTime()


    if not ssVar.openserver_superpurchase_total_buycount then
        ssVar.openserver_superpurchase_total_buycount = 0
    end
    
    local actorid = Actor.getActorId(sysarg)
    local data = gRankMgr_GetValueById(actorid, RANK_OS_SUPER_PURCHASE, 1)
    local myData = BaseFuc_unserialize(data)

    if not myData or myData == "" or myData == 0 then
        myData = {}
    end

    if myData.mySelfTime and not System.isSameDay(myData.mySelfTime, time) then
        myData.myDailyBuyCount = {}
    end

    if not myData.myDailyBuyCount then
        myData.myDailyBuyCount = {}
    end

    if not myData.myBuyCount then
        myData.myBuyCount = 0
    end

    local pack = DataPack.allocPacket(sysarg, LogicCmd.miscSys.sysId, LogicCmd.miscSys.sub.sOpenServerSuperPurchaseData)
    if not pack then return end

    local day = System.getDaysSinceOpenServer()
    local dailyItemList = config.itemList[day]
    if not dailyItemList then
        dailyItemList = config.itemList[#config.itemList]
    end

    local itemLen = #dailyItemList
    DataPack.writeByte(pack, itemLen)
    for idx = 1, itemLen do
        DataPack.writeByte(pack, idx)
        local item = dailyItemList[idx]
        local lastNum = item.buyLimit - (myData.myDailyBuyCount[idx] or 0)
        DataPack.writeShort(pack, lastNum)
        --print("lastNum = "..lastNum)
    end
    DataPack.writeUInt(pack, ssVar.openserver_superpurchase_total_buycount or 0)
    --print("state = "..(ssVar.openserver_superpurchase_total_buycount or 0))
    local rewardCfg = config.Rewards[day]
    if not rewardCfg then
        rewardCfg = config.Rewards[#config.Rewards]
    end
    local len = #rewardCfg
    DataPack.writeByte(pack, len)
    for idx = 1, len do
        DataPack.writeByte(pack, idx)
        local state = 0
        if myData.myDayData and myData.myDayData[idx] and myData.myDayData[idx] >= 1 then
            state = myData.myDayData[idx] 
        elseif (not myData.myDayData or not myData.myDayData[idx] or myData.myDayData[idx] == 0) and 
            ssVar.openserver_superpurchase_total_buycount >= rewardCfg[idx].buyCount and myData.myBuyCount and myData.myBuyCount > 0 then
            state = 1
        end
        DataPack.writeByte(pack, state)
        --print("state = "..state)
    end

    DataPack.flush(pack)

    --DataPack.writeByte(netPack, 1)        -- 活动特有参数
end

-- 操作，返回操作结果，0为成功
function OpenServerSuperPurchaseHandler(sysarg, clientPkt)
    if not IsInOpenServerSuperPurchaseDay() then
        return
    end
    local config = OpenServerCfg.superPurchase
    if config == nil then -- 参数错误
        print("error, config confg error")
        return
    end

    local operType = DataPack.readByte(clientPkt) 
    local Index = DataPack.readByte(clientPkt)

    --print("operType ="..operType)
    --print("Index ="..Index)

    local time = System.getCurrMiniTime()

    --print("time ="..time)

    local ssVar = System.getStaticVar()

    if operType == 1 then
        local buyCount = DataPack.readWord(clientPkt)
        local day = System.getDaysSinceOpenServer()
        local dailyItemList = config.itemList[day]
        if not dailyItemList then
            dailyItemList = config.itemList[#config.itemList]
        end
        if Index > #dailyItemList then
            Actor.sendTipmsg(sysarg, Lang.ScriptTips.OpenServer019, ttFlyTip)
        else
            local actorid = Actor.getActorId(sysarg)
            local data = gRankMgr_GetValueById(actorid, RANK_OS_SUPER_PURCHASE, 1)
            local myData = BaseFuc_unserialize(data)

            if not myData then
                myData = {}
            end

            local item = dailyItemList[Index]
            if not item then
                Actor.sendTipmsg(sysarg, Lang.ScriptTips.OpenServer019, ttFlyTip)
                return
            end

            if myData.mySelfTime and not System.isSameDay(myData.mySelfTime, time) then
                myData.myDailyBuyCount = {}
            end

            if not myData.myDailyBuyCount then
                myData.myDailyBuyCount = {}
            end

            if not myData.myBuyCount then
                myData.myBuyCount = 0
            end

            if not myData.myDailyBuyCount[Index] then
                myData.myDailyBuyCount[Index] = 0
            end

            if item.buyLimit <= myData.myDailyBuyCount[Index] then
                Actor.sendTipmsg(sysarg, Lang.ScriptTips.OpenServer020, ttFlyTip)
                return 
            end

            if buyCount > item.buyLimit - myData.myDailyBuyCount[Index] then
                buyCount = item.buyLimit - myData.myDailyBuyCount[Index]
            end
            local buyCostMoney = item.nowPrice * buyCount
            if buyCostMoney > Actor.getMoneyCount(sysarg, mtYuanbao) then
                Actor.sendItemLack( sysarg, qatYuanbao, 0, buyCostMoney )
                return
            end

            if not Actor.delMoney( sysarg,mtYuanbao,buyCostMoney,LogIds.OpenServerSuperPurchaseLogId,Lang.LogTips.OpenServerSuperPurchase) then
                return
            end

            myData.myBuyCount = myData.myBuyCount + buyCount
            myData.myDailyBuyCount[Index] = myData.myDailyBuyCount[Index] + buyCount

            ssVar.openserver_superpurchase_total_buycount = ssVar.openserver_superpurchase_total_buycount + buyCount

            --print("myData.myBuyCount ="..myData.myBuyCount)
            --print("myData.myDailyBuyCount[Index] ="..myData.myDailyBuyCount[Index])

            local myAwards = GetAwardsByRate( {item}, buyCount )

            if IsBagGridEnough(sysarg, myAwards) then
                GiveCommonAward(sysarg, myAwards, LogIds.OpenServerSuperPurchaseLogId, Lang.LogTips.OpenServerSuperPurchase)
            else
                local actorId = Actor.getActorId(sysarg)
                local title = Lang.ScriptTips.OpenServer017
                local content = Lang.ScriptTips.OpenServer018
                local sex = Actor.getIntProperty(sysarg, PROP_ACTOR_SEX)
                local vocation = Actor.getIntProperty(sysarg, PROP_ACTOR_VOCATION)
                Awards.GiveToMailById(actorId, myAwards, title, content, LogIds.OpenServerSuperPurchaseLogId, Lang.LogTips.OpenServerSuperPurchase, vocation, sex)
            end

            if not myData.sex then
                myData.sex = Actor.getIntProperty(sysarg, PROP_ACTOR_SEX)
                myData.vocation = Actor.getIntProperty(sysarg, PROP_ACTOR_VOCATION)
            end

            myData.mySelfTime = time

            local newData = BaseFuc_serialize(myData)
            gRankMgr_SetRankEx(actorid, RANK_OS_SUPER_PURCHASE, 1, newData)

        end
    elseif operType == 2 then
        local day = System.getDaysSinceOpenServer()
        local rewardCfg = config.Rewards[day]
        if not rewardCfg then
            rewardCfg = config.Rewards[#config.Rewards]
        end
        if Index > #rewardCfg then
            Actor.sendTipmsg(sysarg, Lang.ScriptTips.OpenServer021, ttFlyTip)
            return
        end

        local actorid = Actor.getActorId(sysarg)
        local data = gRankMgr_GetValueById(actorid, RANK_OS_SUPER_PURCHASE, 1)
        local myData = BaseFuc_unserialize(data)

        if not myData then
            Actor.sendTipmsg(sysarg, Lang.ScriptTips.OpenServer022, ttFlyTip)
            return
        end

        local getState = false
        if myData.myBuyCount and myData.myBuyCount > 0 and ((myData.myDayData and myData.myDayData[Index] and myData.myDayData[Index] == 1) or
            ((not myData.myDayData or not myData.myDayData[Index] or myData.myDayData[Index] == 0) and
                ssVar.openserver_superpurchase_total_buycount >= rewardCfg[Index].buyCount))
            then
            getState = true
        end

        if not getState  then
            Actor.sendTipmsg(sysarg, Lang.ScriptTips.OpenServer022, ttFlyTip)
            return
        end

        local rewards = rewardCfg[Index].Awards

        if not myData.myDayData then
            myData.myDayData = {}
        end

        myData.myDayData[Index] = 2
        
        if IsBagGridEnough(sysarg, rewards) then
            GiveCommonAward(sysarg, rewards, LogIds.OpenServerSuperPurchaseLogId, Lang.LogTips.OpenServerSuperPurchase)
        else
            local actorId = Actor.getActorId(sysarg)
            local title = Lang.ScriptTips.OpenServer017
            local content = Lang.ScriptTips.OpenServer018
            local sex = Actor.getIntProperty(sysarg, PROP_ACTOR_SEX)
            local vocation = Actor.getIntProperty(sysarg, PROP_ACTOR_VOCATION)
            Awards.GiveToMailById(actorId, rewards, title, content, LogIds.OpenServerSuperPurchaseLogId, Lang.LogTips.OpenServerSuperPurchase, vocation, sex)
        end

        if not myData.sex then
            myData.sex = Actor.getIntProperty(sysarg, PROP_ACTOR_SEX)
            myData.vocation = Actor.getIntProperty(sysarg, PROP_ACTOR_VOCATION)
        end

        local newData = BaseFuc_serialize(myData)
        gRankMgr_SetRankEx(actorid, RANK_OS_SUPER_PURCHASE, 1, newData)
    end

    SendOpenServerSuperPurchaseData(sysarg)
end





